package com.booksmanager.config;

import com.booksmanager.pojo.User;
import com.booksmanager.utils.RequestSession;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ Author     ：Yan
 * @ Date       ：Created in 14:23 2020/5/20
 * @ Description：
 * @ Modified By：
 * @Version: $
 */
public class InterceptorConfig implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        RequestSession<User> requestSession = new RequestSession<>();
        // 判断用户是否处于登录状态
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies) {
            if(cookie.getName().equals("u_id")) {
                if(cookie.getValue().equals(requestSession.getSessionId())) {
                    // 判断服务器端sessionId与客户端id相同则放行
                    // 判断用户是否登录
                    if(requestSession.getUser() != null) {
                        return  true;
                    }
                }
            }
        }
        // 两个sessionId不同则返回403
        // 403 表示资源拒绝访问
        response.setStatus(403);
        return false;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
